package net.neiquan.neiquandemowithkf.fragment;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;


import com.alibaba.sdk.android.oss.config.Constant;
import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.easemob.helpdeskdemo.HxConstant;
import com.easemob.helpdeskdemo.HxHelper;
import com.easemob.helpdeskdemo.domain.OrderMessageEntity;
import com.easemob.helpdeskdemo.ui.ChatActivity;
import com.easemob.helpdeskdemo.utils.CommonUtils;

import net.neiquan.neiquandemowithkf.R;
import net.neiquan.neiquandemowithkf.activity.ContainerActivity;
import net.neiquan.neiquandemowithkf.application.MyApplication;
import net.neiquan.neiquandemowithkf.utils.SPUtils;
import net.neiquanlib.base.AppBaseFragment;
import net.neiquanlib.numberpicker.entity.CityResult;
import net.neiquanlib.numberpicker.view.AlertCityPicker;
import net.neiquanlib.numberpicker.view.AlertDatePicker;
import net.neiquanlib.numberpicker.view.AlertPickerSingle;
import net.neiquanlib.widget.HorizontalTextItem;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.TimeUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static android.R.attr.id;


/**
 * 作者 : hjb
 * 时间 : 2016/4/25.
 */
public class TabThreeFragment extends AppBaseFragment {
    @InjectView(R.id.one_Item)
    HorizontalTextItem mOneItem;
    @InjectView(R.id.two_Item)
    HorizontalTextItem mTwoItem;
    @InjectView(R.id.three_Item)
    HorizontalTextItem mThreeItem;
    @InjectView(R.id.four_Item)
    HorizontalTextItem mFourItem;
    @InjectView(R.id.five_Item)
    HorizontalTextItem mFiveItem;

    @Override
    public View initRootView() {
        rootView = mInflater.inflate(R.layout.frag_forum, null);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void setViews() {
        setBackGone();
        setTitleTv("论坛");
    }

    @Override
    public void initData() {
        mOneItem.setLeftImgVisible(View.GONE);
        mTwoItem.setLeftImg(R.mipmap.ic_launcher);
        mFourItem.setItemText("我是我的");
        mFourItem.setLeftImgSize(40);
        mThreeItem.setItemTextColor(Color.BLUE);
        mThreeItem.setItemTextSize(30);
    }

    @OnClick({R.id.one_Item, R.id.two_Item, R.id.three_Item, R.id.four_Item, R.id.five_Item})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.one_Item:
                Toast.makeText(getActivity(), "第一个条目", Toast.LENGTH_SHORT).show();
                ContainerActivity.startActivity(getActivity(), PinyinDemoFragment.class, null);
                break;
            case R.id.two_Item:
                Toast.makeText(getActivity(), "第二个条目", Toast.LENGTH_SHORT).show();
                if (MyApplication.getInstance().isLogin()) {
                    if (EMChat.getInstance().isLoggedIn()) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    //加载本地数据库中的消息到内存中
                                    EMChatManager.getInstance().loadAllConversations();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                toChatActivity_();
                            }
                        }).start();
                    } else {
                        //随机创建一个用户并登录环信服务器
                        createRandomAccountAndLoginChatServer();
                    }
                }
                break;
            case R.id.three_Item:
                ArrayList<String> list = new ArrayList<>();
                list.add("男");
                list.add("女");
                new AlertPickerSingle.Builder(getActivity())
                        .setTitle("性别")
                        .setData(list)
                        .setOnItemSelectListener(new AlertPickerSingle.OnItemSelectListener() {
                            @Override
                            public void endSelect(AlertPickerSingle chooser, boolean isCancel, int id, String text) {
                                AppLog.e(text);
                                mThreeItem.setItemText(text);
                            }
                        }).show();
                break;
            case R.id.four_Item:
                DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                Date satrtDate = null;
                try {
                    satrtDate = df.parse("20/12/1991");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
//                 satrtDate = TimeUtil.getDateAfter(new Date(), 1);// 开始日期一天后
                final Date endDate = TimeUtil.getDateAfter(new Date(), 0);
                new AlertDatePicker.Builder(getActivity())
                        .setTitle("日期选择")
                        .setDate(satrtDate, endDate)
                        .setDateSelectListener(new AlertDatePicker.OnDateSelectListener() {
                            @Override
                            public void endSelect(Date selectDate, String selectDateStr, boolean isCancel) {
                                AppLog.e("selectDateStr" + selectDateStr);
                                mFourItem.setItemText(selectDateStr);
                            }
                        }).show();
                break;
            case R.id.five_Item:
                new AlertCityPicker.Builder(getActivity())
                        .setTitle("城市选择")
                        .setOnCitySelectListener(new AlertCityPicker.OnCitySelectListener() {
                            @Override
                            public void endSelect(CityResult cityResult, boolean isCancel) {
                                AppLog.e("cityResult" + cityResult.getProviceName());
                                mFiveItem.setItemText(cityResult.getProviceName());
                            }
                        }).show();

                break;
        }
    }

    private void toChatActivity_() {


//                SPUtils.saveToSP(id, id);
//                OrderMessageEntity entity1 = new OrderMessageEntity(1, commodityInfo.getCommodityName(), "商品号：" + commodityInfo.getId() + "", "￥" + commodityInfo.getSortPrice(),
//                        "\n" + commodityInfo.getFirstType() + ":" + commodityInfo.getAttribute(), commodityInfo.getPicList().get(0).getImgUrl(), commodityInfo.getPicList().get(0).getImgUrl());
//                AppLog.e("-------" + entity1.toString());
//                startActivity(new Intent(GoodsDetailActivity.this, ChatActivity.class).putExtra(
//                        Constant.CUSTOMER_MESSAGE, entity1));
        OrderMessageEntity entity1 = new OrderMessageEntity(1, "这里是商品名字", "商品号：" + "商品id" + "", "￥" + "78(price)",
                        "\n" + "品牌" + ":" + "oppo", "http://www.pptbz.com/pptpic/UploadFiles_6909/201110/20111014111307895.jpg", "http://www.pptbz.com/pptpic/UploadFiles_6909/201110/20111014111307895.jpg");
                startActivity(new Intent(getActivity(), ChatActivity.class).putExtra(
                        HxConstant.INTENT_CODE_IMG_SELECTED_KEY, entity1));
    }

    private void createRandomAccountAndLoginChatServer() {
        // 自动生成账号
        final String randomAccount = CommonUtils.getRandomAccount();
        final String userPwd = HxConstant.DEFAULT_ACCOUNT_PWD;
        progressDialog = getProgressDialog();
        progressDialog.setMessage(getResources().getString(R.string.system_is_regist));
        progressDialog.show();
        createAccountToServer(randomAccount, userPwd, new EMCallBack() {

            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //登录环信服务器
                        loginHuanxinServer(randomAccount, userPwd);
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int errorCode, final String message) {
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (!getActivity().isFinishing()) {
                            progressDialog.dismiss();
                        }
                        if (errorCode == EMError.NONETWORK_ERROR) {
                            Toast.makeText(getActivity(), "网络不可用", Toast.LENGTH_SHORT).show();
                        } else if (errorCode == EMError.USER_ALREADY_EXISTS) {
                            Toast.makeText(getActivity(), "用户已存在", Toast.LENGTH_SHORT).show();
                        } else if (errorCode == EMError.UNAUTHORIZED) {
                            Toast.makeText(getActivity(), "无开放注册权限", Toast.LENGTH_SHORT).show();
                        } else if (errorCode == EMError.ILLEGAL_USER_NAME) {
                            Toast.makeText(getActivity(), "用户名非法", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), "注册失败：" + message, Toast.LENGTH_SHORT).show();
                        }
                        finish();
                    }
                });
            }
        });
    }

    //注册用户
    private void createAccountToServer(final String uname, final String pwd, final EMCallBack callback) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    EMChatManager.getInstance().createAccountOnServer(uname, pwd);
                    if (callback != null) {
                        callback.onSuccess();
                    }
                } catch (EaseMobException e) {
                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.getMessage());
                    }
                }
            }
        });
        thread.start();
    }

    private ProgressDialog getProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    progressShow = false;
                }
            });
        }
        return progressDialog;
    }

    public void loginHuanxinServer(final String uname, final String upwd) {
        progressShow = true;
        progressDialog = getProgressDialog();
        progressDialog.setMessage(getResources().getString(R.string.is_contact_customer));
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        // login huanxin server
        EMChatManager.getInstance().login(uname, upwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                if (!progressShow) {
                    return;
                }
                HxHelper.getInstance().setCurrentUserName(uname);
                HxHelper.getInstance().setCurrentPassword(upwd);
                try {
                    EMChatManager.getInstance().loadAllConversations();
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
                toChatActivity_();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                if (!progressShow) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(),
                                getResources().getString(R.string.is_contact_customer_failure_seconed) + message,
                                Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            }
        });
    }

    private boolean progressShow;
    private ProgressDialog progressDialog;
}
